<?php

namespace app\common\model\shop;

use app\common\library\Auth;
use app\common\model\Acct;
use app\common\model\Acctmoneylog;
use app\common\model\Address;
use app\common\model\Custom;
use app\common\model\Distribution;
use app\common\model\Distributionconfig;
use app\common\model\Distributionregion;
use app\common\model\shop\goods\Acct as GoodsAcct;
use app\common\model\Special;
use app\common\model\User;
use app\common\model\user\Alloca;
use app\common\model\user\Commission;
use app\common\model\user\Custom as UserCustom;
use Hyc;
use Jdy;
use think\Db;
use think\Exception;
use think\Log;
use think\Model;
use think\Queue;
use traits\model\SoftDelete;

class Order extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'shop_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text',
        'pay_time_text',
        'createtime_text',
        'finished_time_text',
        'express_com_text',
        'pay_image_str',
        'day_int',
        'timeout',

    ];
    public function getTimeoutAttr($v, $d)
    {
        if (isset($data['createtime']) && $data['createtime']) {

            if ($d['createtime'] + (10 * 60) < time()) {
                return false;
            }
        }
        return true;
    }

    public function getDayIntAttr($v, $d)
    {
        if (isset($data['distribution_id']) && $data['distribution_id']) {
            $distribution = Distribution::get($d['distribution_id']);
            if ($d['createtime'] > 0 && $distribution) {
                return ceil(($d['createtime'] + ($distribution->day * 86400) - time()) / 86400);
            } else {
                return 0;
            }
        }
    }

    public function getPayImageStrAttr($value, $data)
    {
        if (isset($data['pay_image']) && $data['pay_image']) {
            $images = explode(',', $data['pay_image']);
            foreach ($images as &$v) {
                $v = cdnurl($v, true);
            }
            return $images;
        }
        return [];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'),  '0.1' => __('Status 0.1'), '0.5' => __('Status 0.5'), '0.6' => __('Status 0.6'), '1' => __('Status 1'), '99' => __('Status 99'), '-1' => __('审核失败')];
    }

    public function getExpressComList()
    {
        return ['SF' => __('Express_com sf'), 'HTKY' => __('Express_com htky'), 'ZTO' => __('Express_com zto'), 'STO' => __('Express_com sto'), 'YTO' => __('Express_com yto'), 'YD' => __('Express_com yd'), 'YZPY' => __('Express_com yzpy'), 'EMS' => __('Express_com ems'), 'JD' => __('Express_com jd'), 'UC' => __('Express_com uc'), 'DBL' => __('Express_com dbl'), 'JTSD' => __('Express_com jtsd'), 'ZYE' => __('Express_com zye'), 'ZJS' => __('Express_com zjs')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getFinishedTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['finished_time']) ? $data['finished_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getExpressComTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['express_com']) ? $data['express_com'] : '');
        $list = $this->getExpressComList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setFinishedTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function custom()
    {
        return $this->belongsTo('app\common\model\Custom', 'custom_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function incustom()
    {
        return $this->belongsTo('app\common\model\Custom', 'custom_id', 'id', [], 'INNER')->setEagerlyType(0);
    }

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function distribution()
    {
        return $this->belongsTo('app\common\model\Distribution', 'distribution_id', 'id', [], 'LEFT')->setEagerlyType(1);
    }
    public function wl()
    {
        return $this->belongsTo('app\common\model\Category', 'express_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function ordergoods()
    {
        return $this->hasMany('app\common\model\shop\Ordergoods', 'order_id', 'id');
    }
    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            if (array_key_exists('status', $row->getChangedData())) {
                if ($row['type'] == 0) {
                    $total_ed = bcadd($row->send_fee, $row->original_price, 2);
                } else {
                    $total_ed = $row->original_price;
                }
                if ($row->status == '99') {
                    $row->finished_time = time();
                    foreach ($row->ordergoods as $v) {
                        $info = json_decode($v->goods_info, true);
                        $goods = Goods::get($info['id']);
                        if ($goods) {
                            $goods->setInc('sale_num', $v->total);
                        }
                    }
                    //结算佣金
                    $user = User::get($row->user_id);
                    if ($user && $user['is_commission']) {
                        Commission::addCommission($row);
                    }
                    //子平台收益
                    Commission::addAcctCommission($row);
                } elseif ($row->status == '1') {
                    // if ($total_ed > 0 && $row->send_type == 1) {
                    //     $acct = Acct::get($row->acct_id);
                    //     if (($acct->admin->money ?? 0) < $total_ed) {
                    //         exception('授信余额不足请充值');
                    //     }
                    //     Acctmoneylog::money(-$total_ed, $acct->admin_id, '订单下单', '', $row->id);
                    // }
                    // 快递公司
                    // {{thing1.DATA}}

                    // 快递单号
                    // {{character_string2.DATA}}

                    // 收货地址
                    // {{thing9.DATA}}

                    // 订单金额
                    // {{amount11.DATA}}

                    // 客户姓名
                    // {{name14.DATA}}
                    // $s = sendSubTemplateMsg(
                    //     $row->user,
                    //     "F_8cacwNWQyOI0pC00SfyttCB7jdM17zQcjWQb23O6U",
                    //     [
                    //         'thing1' => ['value' => $row->wl['name'] ?? '暂无'],
                    //         'character_string2' => ['value' => $row->express_no ?? '暂无'],
                    //         'thing9' => ['value' => $row['consign_address'] ?? '暂无'],
                    //         'amount11' => ['value' => $row->pay_fee],
                    //         'name14' => ['value' => $row->custom['name'] ?? '暂无'],
                    //     ]
                    // );
                    // Log::error('订阅消息1' . var_export($s, 1));
                    // Queue::later(10 * 86400, 'app\common\job\OrderJob@confirm', $row->id, $queue = '1243confirm');
                } elseif ($row->status == '0.1') {
                    $row->pay_time = time();
                    $alloca = Alloca::where('user_id', $row->user_id)->find();
                    if ($alloca) {
                        $alloca->setInc('effective', $row->total_fee);
                    }
                    $usercustom = UserCustom::where('custom_id', $row->custom_id)->find();
                    if ($usercustom) {
                        $usercustom->setInc('effective', $row->total_fee);
                    }

                    //扣除库存
                    $ordergoods = Ordergoods::where('order_id', $row->id)->select();
                    foreach ($ordergoods as $v) {

                        $acctgoods = Goods::where('id', $v->goods_info_json['id'])->find();
                        if (!$acctgoods) {
                            exception("商品不存在");
                        }
                        $acctgoods->stock -= $v->total;
                        $acctgoods->save();
                        Goodsstockout::create([
                            'goods_id' => $v->goods_info_json['id'],
                            // 'acct_id' => $row->acct_id,
                            'num' => $v->total,
                            'order_no' => $row->order_no,
                        ], true);
                    }
                } elseif ($row->status == '0.5') {
                    // if ($row->acct_id == 50 || $row->acct_id == 67) {
                    $api = new Jdy(['acct_id' => 50]);
                    $api->addOrder($row);
                    // }

                    // if ($row->send_type == 1 && $row->acct_id != 50) {

                    Goodsstockout::where('order_no', $row->order_no)->delete();
                    //退还库存
                    $ordergoods = Ordergoods::where('order_id', $row->id)->select();
                    foreach ($ordergoods as $v) {
                        $acctgoods_pl = Goods::where('id', $v->goods_info_json['id'])->find();
                        if ($acctgoods_pl) {
                            $acctgoods_pl->stock = $acctgoods_pl->stock - $v->total;
                            $acctgoods_pl->save();
                        }


                        $acctgoods = Goods::where('id', $v->goods_info_json['id'])->find();
                        if ($acctgoods) {
                            $acctgoods->stock = $acctgoods->stock + $v->total;
                            $acctgoods->save();
                        }

                        Goodsstockout::create([
                            'goods_id' => $v->goods_info_json['id'],
                            // 'acct_id' => 50,
                            'num' => $v->total,
                            'order_no' => $row->order_no,
                        ], true);
                        // }
                    }
                } elseif ($row->status == '-1') {
                    $acct = Acct::get($row->acct_id);
                    $log = Acctmoneylog::get(['memo' => '订单下单', 'source' => $row->id, 'user_id' => $acct->admin_id]);
                    if ($log) {
                        Acctmoneylog::money($total_ed, $acct->admin_id, '订单审核失败返还', '', $row->id);
                    }
                }
            }
        });
    }
    public static function yuOrder($goods_info, $distribution_id = 0, $address_id = 0, $custom_id = 0, $type = 0)
    {
        $goods_list = [];
        $check_stock = true;
        $total_money = $total = $total_original_price = $pay_fee = $total_fee = $send_fee = $weight = $only_fx_price = 0;
        foreach ($goods_info as $v) {
            $product = Goods::get(['id' => $v['id'], 'sale_switch' => 1]);
            if (!$product) {
                exception('商品【' . $v['title'] . '】不存在');
            }
            $product['num'] = $v['num'];
            if ($product['stock'] < $v['num']) {
                $check_stock = false;
            }
            if ($product['price'] > 0) {
                $original_price = $product['purchase_price'];
                $goods_price = $product['price'];
            }
            if (isset($v['pay_money']) && $v['pay_money'] > $goods_price) {
                $pay_money = $v['pay_money'];
            } else {
                $pay_money = $goods_price;
            }
            $product['pay_money'] = $pay_money;
            $product['original_price'] = $original_price;
            $product['total_money'] = bcmul($v['num'], $goods_price, 2);
            $product['total_original_price'] = bcmul($v['num'], $original_price, 2);
            $product['pay_fee'] = bcmul($v['num'], $pay_money, 2);
            $total_original_price += $product['total_original_price'];
            $total_fee += $product['total_money'];
            $total_money += $product['pay_fee'];
            $pay_fee += $product['pay_fee'];
            $total += $v['num'];
            $product['total_weight'] = bcmul($product['weight'], $product['num'], 2);
            $weight += $product['total_weight'];

            if ($product['only_fx'] == 1) {
                $only_fx_price += $product['total_money'];
            }

            unset($product['content']);
            array_push($goods_list, $product);
        }

        if ($address_id) {
            $info = Address::get($address_id);
            if (!$info) {
                exception('请完善客户资料');
            }
            $city = $info['city'];
            $area_id = $info['area_id'];
        } else {
            $info = Custom::get($custom_id);
            if (!$info) {
                exception('客户错误,请确认客户信息');
            }
            $city = $info['city'];
            $area_id = $info['area_id'];
        }

        $arr = explode('/', $city);

        $total_weight = $weight;
        $dis = Distribution::get($distribution_id);
        $dispid = Distribution::get($dis['pid']);
        if ($type == 1 && empty($arr[2])) {
            exception('请完善客户资料');
        }
        $distribution = Distributionregion::whereLike('area_id', $area_id)->where('pid', $distribution_id)->find();
        if ($type == 1 && !$distribution) {
            exception('请完善客户资料');
        }
        if ($type == 1 && $dis['weight'] > $total_weight) {
            exception('下单重量不得小于起送重量');
        }
        if ($city && !$area_id) {
            $info->province_id = db('cnarea')->where('short_name|name', 'like', "%{$arr[0]}%")->where('level', 1)->value('area_code');
            $info->city_id = db('cnarea')->where('short_name|name', 'like', "%{$arr[1]}%")->where('level', 2)->value('area_code');
            $info->area_id = db('cnarea')->where('short_name|name', 'like', "%{$arr[2]}%")->where('level', 3)->value('area_code');
            $info->save();
        }
        if ($distribution) {
            $send_fee = $distribution->send_fee;
            $expense = 0;
            if ($weight > 0) {
                if ($weight > $distribution->weight) {
                    // $weight -= $distribution->weight;
                    $config = Distributionconfig::where(['pid' => $distribution->id])->order('weight asc')->select();
                    foreach ($config as $vv) {
                        if ($vv->weight >= $weight) {
                            $expense = $vv->send_fee;
                            break;
                        } else {
                            $expense = $vv->send_fee;
                        }
                    }
                }
            }

            if ($send_fee > 0 && $weight > 0 && $expense > 0) {
                $send_fee = ceil($weight) * $expense;
                // $send_fee = bcadd($send_fee, $czf, 2);
            }

            if ($dis['type'] == '0') {
                $pay_fee = bcadd($pay_fee, $send_fee, 2);
            }
        }
        return compact('goods_list', 'total_fee', 'pay_fee', 'send_fee', 'total', 'total_weight', 'total_original_price', 'only_fx_price', 'total_money', 'check_stock');
    }

    public static function addOrder($custom_id, $address_id, $uid, $arr, $pay_image, $distribution, $remark = '', $orderid = 0)
    {
        try {
            $user = User::get($uid);
            $custom = Custom::get($custom_id);
            $acct = Acct::get($user->acct_id);

            if ($address_id) {
                $address = Address::get($address_id);
                if (!$address || $address->custom_id != $custom_id) {
                    exception('错误的地址');
                }
            }
            if ($pay_image) {
                $status = '0';
            } else {
                $status = '-0.5';
            }
            $distributionmodel = Distribution::get($distribution);
            $dispid = Distribution::get($distributionmodel['pid']);
            if ($dispid['title'] == '物流') {
                $status = '-0.4';
            }
            // if ($distributionmodel['type'] == 0) {
            //     $total_ed = bcadd($arr['send_fee'], $arr['total_original_price'], 2);
            // } else {
            //     $total_ed = $arr['total_original_price'];
            // }
            // if (($acct->admin->money ?? 0) < $total_ed) {
            //     exception('下单权益受限，请联系管理员');
            // }
            $order = new Order();
            if ($orderid) {
                $order = $order->get($orderid);
                if ($order->timeout == false) {
                    exception('超时不可修改');
                }
                $sn = $order->order_no;
                $order->isUpdate(true);
            } else {
                $order->isUpdate(false);
                $sn = sn('shop_order', 'order_no', 'NO');
            }
            $data = [
                'order_no' => $sn,
                'user_id' => $uid,
                'custom_id' => $custom_id,
                'total' => $arr['total'],
                'total_weight' => $arr['total_weight'],
                'total_fee' => $arr['total_fee'],
                'original_price' => $arr['total_original_price'],
                'only_fx_price' => $arr['only_fx_price'],
                'remark' => $remark,
                'distribution_id' => $distribution,
                'type' => $distributionmodel['type'],
                'pay_fee' => $arr['pay_fee'],
                'consign_name' => $custom['name'],
                'consign_mobile' => $custom['phone'],
                'consign_address' => ($address->city ?? $custom['city']) . '/' . ($address->address ?? $custom['address']),
                'pay_image' => $pay_image,
                'status' => $status,
                'send_fee' => $arr['send_fee'],
                'acct_id' => $user->acct_id
            ];

            $custom->lasttime = time();
            $custom->save();
            $res = $order->allowField(true)->save($data);

            if ($res) {
                Ordergoods::where('order_id', $orderid)->delete();
                $array = [];
                foreach ($arr['goods_list'] as $v) {
                    if ($v['limited'] > 0) {
                        if ($v['custom'] == 0 && $v['limited'] < $v['num']) {
                            exception('【' . $v['title'] . '】商品限制购买数量' . $v['limited'] . '/' . $v['unit']);
                        }
                        if ($v['custom'] == 1 && $v['limited'] > $v['num']) {
                            exception('【' . $v['title'] . '】商品起购数量' . $v['limited'] . '/' . $v['unit']);
                        }
                    }
                    array_push($array, [
                        'order_id' => $order->id,
                        'goods_info' => json_encode($v),
                        'price' => $v['price'],
                        'pay_price' => $v['pay_money'],
                        'original_price' => $v['original_price'],
                        'total_original_price' => $v['total_original_price'],
                        'total' => $v['num'],
                        'total_weight' => $v['total_weight'],
                        'acct_id' => $user->acct_id,
                    ]);
                }
                $Ordergoods = new Ordergoods();
                $Ordergoods->allowField(true)->saveAll($array);

                // Acctmoneylog::money(-$total_ed, $acct->admin_id, '订单下单', '', $order->id);
            } else {
                exception('下单失败');
            }
            $day = config('site.del_custom_day');
            queue('app\common\job\DelCustom', $custom->id, $day * 86400, 'del_custom1243');
        } catch (Exception $e) {
            exception($e->getMessage());
        }
        return ['order_id' => $order->id, 'check_stock' => $arr['check_stock'] ?? true];
    }
}
